package message

import (
	"crypto/sha1"
	"encoding/hex"
	"fmt"
	"gq_volunteer_platform/bean"
	"sort"

	"github.com/gin-gonic/gin"
)

const token = "hnsjb"

func Test(c *gin.Context) {

	var req struct {
		Signature string `form:"signature" binding:"max=255"`
		Timestamp string `form:"timestamp" binding:"max=255"`
		Nonce     string `form:"nonce" binding:"max=255"`
		Echostr   string `form:"echostr" binding:"max=255"`
	}

	if err := c.ShouldBindQuery(&req); err != nil {
		bean.Log.Warning(err.Error())
		c.String(400, err.Error())
		return
	}

	// 获取URL参数
	signature := req.Signature
	timestamp := req.Timestamp

	nonce := req.Signature
	echostr := req.Echostr
	isValid := verifySignature(signature, timestamp, nonce)
	fmt.Println("jldtx", isValid)

	c.String(200, echostr)

	// // 验证签名
	// if verifySignature(signature, timestamp, nonce) {
	// 	// 签名验证通过，返回echostr
	// 	c.String(200, echostr)
	// } else {
	// 	c.String(200, "不一致")
	// }
}

func verifySignature(signature, timestamp, nonce string) bool {
	// 1. 字典序排序
	strs := []string{nonce, timestamp, token}
	sort.Strings(strs)

	// 2. 拼接字符串
	combined := ""
	for _, str := range strs {
		combined += str
	}

	// 3. SHA1加密
	h := sha1.New()
	h.Write([]byte(combined))
	sha1Hash := hex.EncodeToString(h.Sum(nil))

	// 4. 比较签名
	return sha1Hash == signature
}
